package cj.web.kly.controllers;

import java.io.File;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.utils.DateUtils;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.kly.constants.NewReleaseStateEnum;
import cj.web.kly.constants.NewTypeEnum;
import cj.web.kly.constants.SubjectStatusEnum;
import cj.web.kly.constants.SubjectTypeEnum;
import cj.web.kly.domain.News;
import cj.web.kly.domain.Subject;
import cj.web.kly.service.SubjectService;
import cj.web.login.controllers.BaseController;

@Path("/subject")
public class SubjectController extends BaseController{
	
	private static String NOT_SEARCH = "NOT_SEARCH";

	private static Logger logger = Logger.getLogger(SubjectController.class.getName());
	
	@Autowired
	private SubjectService subjectService;
	
	@Get("show")
	public String show(Model model,Subject subject) {
	
		return "/views/kly/subjectList.vm";
	}
	
	@Post("getNewsList")
	public String queryNewsList(News news,Invocation inv) throws ParseException {
		
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
		Map configRep = (Map) dictionaryInfoMap.get("configRep");
		String not_in_news_columnsid=configRep.get(NOT_SEARCH).toString();//不显示新闻
	
		//当前页  
		news.setStart((news.getPage()-1)*news.getRows());
		news.setLength(news.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = subjectService.queryNews(news,not_in_news_columnsid);
		List<News> objs = (List<News>) rep.get("newslis");
		for(News obj:objs){
			obj.setReleaseStateName(NewReleaseStateEnum.getName(obj.getReleaseState()));
			obj.setReleaseAt(DateUtils.formatDateStr(obj.getReleaseAt(),DateUtils.DATE_FULL_STR));
			obj.setStickAt(obj.getStickAt()==null?"":obj.getStickAt().toString());
			obj.setTypeName(NewTypeEnum.getName(obj.getType()));
		}
		
		int size = (int) rep.get("size");
		
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}

	@Post("getList")
	public String queryList(Subject subject) {
	
		//当前页  
		subject.setStart((subject.getPage()-1)*subject.getRows());
		subject.setLength(subject.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = subjectService.query(subject);
		List<Subject> objs = (List<Subject>) rep.get("subjectlis");
		
		for(Subject obj:objs){
			obj.setTypeName(SubjectTypeEnum.getName(obj.getType()));
			obj.setStatusName(SubjectStatusEnum.getName(obj.getStatus()));
		}
		
		int size = (int) rep.get("size");
		
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model)
	{
		model.add("subjectTypeEnum",EnumSet.allOf(SubjectTypeEnum.class));
		model.add("subjectStatusEnum",EnumSet.allOf(SubjectStatusEnum.class));
		return "/views/kly/subjectDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,Subject subject,HttpServletRequest request,
			@Param("uploadimage") MultipartFile file,
			@Param("uploadimageMin") MultipartFile fileMin)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		subject.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		subject.setCreateUser(returnSessionObj(request).getAccount());
		subject.setUpdateUser(returnSessionObj(request).getAccount());
		
		try{
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                subject.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
	        
	        // 判断文件是否为空  
	        if (!fileMin.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(fileMin.getOriginalFilename()); 
	                // 转存文件  
	                fileMin.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                subject.setCarouselImageMin(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        }
			
			subjectService.create(subject);
		}catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id)
	{
		Subject subject = subjectService.queryById(id);

		model.add("subject", subject);
		model.add("subjectTypeEnum",EnumSet.allOf(SubjectTypeEnum.class));
		model.add("subjectStatusEnum",EnumSet.allOf(SubjectStatusEnum.class));
		return "/views/kly/subjectEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,Subject subject,HttpServletRequest request,
			@Param("uploadimage") MultipartFile file,
			@Param("uploadimageMin") MultipartFile fileMin)
	{
		JSONObject jo = new JSONObject();
		
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		subject.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                subject.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
	        
	        // 判断文件是否为空  
	        if (!fileMin.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(fileMin.getOriginalFilename()); 
	                // 转存文件  
	                fileMin.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                subject.setCarouselImageMin(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			subjectService.update(subject);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			subjectService.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	@Get("updateStatusById")
	public String updateStatusById(Model model,@Param("Ids") String Ids)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			subjectService.updateStatusById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
}